package com.loto.webapp.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.struts2.ServletActionContext;

import com.loto.webapp.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ValidateCodeAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1323273099772372611L;
	private ByteArrayInputStream inputStream;
	public String execute() {
		try {
			this.setInputStream(generateImage());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	private ByteArrayInputStream generateImage() throws IOException {

		BufferedImage image = new BufferedImage(100, 20,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 100, 20);
		drawbg(g);
		drawValidateCode(g);
		ByteArrayInputStream input = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", bos);
		byte[] buf = bos.toByteArray();
		input = new ByteArrayInputStream(buf);
		return input;
	}

	/**
	 * backGround Draw
	 */
	private void drawbg(Graphics g) {

		Random rand = new Random();
		int randx;
		int randy;
		for (int i = 0; i < rand.nextInt(100) + 500; i++) {
			g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand
					.nextInt(255)));
			randx = rand.nextInt(100);
			randy = rand.nextInt(20);
			g.drawLine(randx, randy, randx, randy);
		}
	}

	/**
	 * code draw
	 */
	private void drawValidateCode(Graphics g) {

		String code = generateCode();
		Random rand = new Random();
		int x = 0;
		Font font = new Font("Times New Roman", Font.PLAIN, 18);
		g.setFont(font);
		for (int i = 0; i < code.length(); i++) {
			int y = 20 - rand.nextInt(4);
			g.setColor(new Color(rand.nextInt(150), rand.nextInt(150), rand
					.nextInt(150)));
			g.drawString(code.substring(i, i + 1), x, y);
			x += 20;
		}
	}

	/**
	 * code generate
	 */
	private String generateCode() {

		Random rand = new Random();
		StringBuffer sbr = new StringBuffer(
				"123456789");//"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
		int codeLen = 4;
		StringBuffer codeSbr = new StringBuffer();
		for (int i = 0; i < codeLen; i++) {
			int select = rand.nextInt(sbr.length());
			codeSbr.append(sbr.charAt(select));
			sbr.deleteCharAt(select);
		}
		setSession("ValidateCode", codeSbr.toString());
		return codeSbr.toString();
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}
}
